/**
 * Configuration Validator
 * Provides validation for configuration files using the new layered validation architecture
 */

const ValidatorManager = require('./validators/validator-manager');

// Initialize validator manager
const validatorManager = ValidatorManager.getInstance();

/**
 * Validate configuration object using the new validation architecture
 * @param {Object} config - Configuration object to validate
 * @param {Object} options - Validation options
 * @returns {Object} Validation result with success status and errors
 */
function validateConfig(config, options = {}) {
  if (!config || typeof config !== 'object') {
    return {
      success: false,
      error: 'Configuration must be a valid object',
      errors: ['Configuration must be a valid object']
    };
  }

  try {
    // Use the new validator manager
    const result = validatorManager.validateConfig(config, options);

    // Adapt the result format to maintain backward compatibility
    if (result.success) {
      return {
        success: true,
        data: result.data || config
      };
    } else {
      const errors = result.errors ? result.errors.map(err => err.message || `${err.field}: ${err.message}`) : [result.error];

      return {
        success: false,
        error: result.error || 'Configuration validation failed',
        errors: errors
      };
    }
  } catch (error) {
    return {
      success: false,
      error: 'Validation error occurred',
      errors: [error.message]
    };
  }
}

/**
 * Validate configuration file and return parsed configuration
 * @param {string} configPath - Path to configuration file
 * @param {Object} options - Validation options
 * @returns {Object} Validation result with parsed configuration
 */
async function validateConfigFile(configPath, options = {}) {
  const fs = require('fs');
  const path = require('path');

  try {
    if (!fs.existsSync(configPath)) {
      return {
        success: false,
        error: 'Configuration file not found',
        errors: [`File not found: ${configPath}`],
        configPath
      };
    }

    const configData = fs.readFileSync(configPath, 'utf8');
    const config = JSON.parse(configData);

    const validationResult = validateConfig(config, options);

    if (!validationResult.success) {
      return {
        ...validationResult,
        configPath
      };
    }

    return {
      success: true,
      data: config,
      configPath
    };
  } catch (error) {
    return {
      success: false,
      error: 'Invalid JSON format',
      errors: [error.message],
      configPath
    };
  }
}

/**
 * Create validation error message with suggestions
 * @param {Array} errors - Array of validation errors
 * @returns {string} Formatted error message with suggestions
 */
function formatValidationErrors(errors) {
  let message = 'Configuration validation failed:\n';

  errors.forEach((error, index) => {
    message += `  ${index + 1}. ${error}\n`;
  });

  // Add recovery suggestions
  message += '\nSuggestions:\n';
  message += '   1. Check JSON syntax (use online JSON validator)\n';
  message += '  2. Ensure all required fields are present\n';
  message += '   3. Verify field types and formats\n';
  message += '  4. Check config-schema.json for requirements\n';

  return message;
}

/**
 * Create a minimal default configuration
 * @returns {Object} Default configuration object
 */
function createDefaultConfig() {
  // Use the new TestConfigFactory to create a consistent default config
  try {
    const TestConfigFactory = require('./factories/testing-config-factory');
    return TestConfigFactory.createFullConfig();
  } catch (error) {
    // Fallback to a hardcoded default if factory is unavailable
    return {
      version: '1.0.0',
      current_provider_model: 'tencent-hunyuan-vision',
      providers: {
        tencent: {
          base: 'https://api.hunyuan.cloud.tencent.com',
          api_key: '',
          models: [
            {
              id: 'hunyuan-vision',
              name: 'Hunyuan Vision',
              type: 'vision',
              capabilities: ['image_analysis', 'ui_analysis', 'design_tokens'],
              max_tokens: 4096,
              supports_vision: true,
              enabled: true
            }
          ]
        }
      },
      http_server: {
        port: 3000,
        auto_start: true,
        host: 'localhost'
      },
      logging: {
        level: 'info',
        retention_days: 30,
        file_enabled: true,
        console_enabled: true
      },
      mcp: {
        server_name: 'vision-analyzer',
        server_version: '1.0.0',
        timeout: 30000
      },
      features: {
        auto_model_selection: true,
        cache_analysis: true,
        debug_mode: false
      }
    };
  }
}

/**
 * Validate provider configuration
 * @param {Object} provider - Provider configuration to validate
 * @param {Object} options - Validation options
 * @returns {Object} Validation result
 */
function validateProviderConfig(provider, options = {}) {
  if (!provider || typeof provider !== 'object') {
    return {
      success: false,
      error: 'Provider configuration must be a valid object',
      errors: ['Provider configuration must be a valid object']
    };
  }

  try {
    // Use the new validator manager
    const result = validatorManager.validateProvider(provider, options);

    // Adapt the result format to maintain backward compatibility
    if (result.success) {
      return {
        success: true,
        data: result.data || provider
      };
    } else {
      const errors = result.errors ? result.errors.map(err => err.message || `${err.field}: ${err.message}`) : [result.error];

      return {
        success: false,
        error: result.error || 'Provider configuration validation failed',
        errors: errors
      };
    }
  } catch (error) {
    return {
      success: false,
      error: 'Provider validation error occurred',
      errors: [error.message]
    };
  }
}

/**
 * Validate model configuration (now integrated into provider validation)
 * @param {Object} model - Model configuration to validate
 * @param {Object} options - Validation options
 * @returns {Object} Validation result
 */
function validateModelConfig(model, options = {}) {
  // Model validation is now handled as part of provider validation
  // This function is kept for backward compatibility
  if (!model || typeof model !== 'object') {
    return {
      success: false,
      error: 'Model configuration must be a valid object',
      errors: ['Model configuration must be a valid object']
    };
  }

  // Create a minimal provider wrapper for the model
  const providerWrapper = {
    base: 'https://api.test.com', // Dummy base URL
    api_key: 'test_key', // Dummy API key
    models: [model]
  };

  return validateProviderConfig(providerWrapper, options);
}

/**
 * Validate HTTP server configuration (now integrated into config validation)
 * @param {Object} httpConfig - HTTP server configuration to validate
 * @param {Object} options - Validation options
 * @returns {Object} Validation result
 */
function validateHttpServerConfig(httpConfig, options = {}) {
  // HTTP server validation is now handled as part of config validation
  // This function is kept for backward compatibility
  if (!httpConfig || typeof httpConfig !== 'object') {
    return {
      success: false,
      error: 'HTTP server configuration must be a valid object',
      errors: ['HTTP server configuration must be a valid object']
    };
  }

  // Create a minimal config wrapper for the HTTP server section
  const configWrapper = {
    version: '1.0.0',
    current_provider_model: 'test-test-model',
    providers: {
      test: {
        base: 'https://api.test.com',
        api_key: 'test_key',
        models: []
      }
    },
    http_server: httpConfig
  };

  const result = validateConfig(configWrapper, options);

  if (result.success) {
    return {
      success: true,
      data: httpConfig
    };
  } else {
    // Filter errors to only include HTTP server related errors
    const httpErrors = result.errors.filter(err => err.includes('http_server'));
    return {
      success: false,
      error: 'HTTP server configuration validation failed',
      errors: httpErrors.length > 0 ? httpErrors : result.errors
    };
  }
}

module.exports = {
  validateConfig,
  validateConfigFile,
  validateProviderConfig,
  validateModelConfig,
  validateHttpServerConfig,
  formatValidationErrors,
  createDefaultConfig
};